const rootUrl='http://localhost:8000';
let login_id='';
let login_token='';
module.exports={
    get(router,data,cb){
        wx.request({
            url: `${rootUrl}${router}`,
            data: data,
            success(data){
                cb(data);
            }
        })
    },
    hasUserData(){
        return !!login_id;
    },
    setUserData(_id,_token){
        login_id=_id;
        login_token=_token;
    },
    getUserData(){
        return {login_id:login_id,login_token:login_token};
    },
    userRequest(data,cb,loaddingText='获取数据中',method='get'){
        let getData=function(){
            data.login_id=login_id;
            data.login_token=login_token;
            wx.request({
                url: `${rootUrl}/user`,
                data: data,
                method:method,
                success(data){
                    wx.hideLoading();
                    if(data.data.code==200){
                        cb(data.data.data);
                    }else{
                        wx.showToast({
                            title: data.data.msg,
                            icon: 'none',
                            duration: 2000
                        })
                    }
                }
            })
        }
        if(!login_id){
            let that=this;
            wx.showLoading({
                title: '验证身份中...',
                mask:true,
                success:()=>{
                    wx.login({
                        success: res => {
                            that.get(
                                '/user/weChatLogin', {
                                    code: res.code
                                },
                                function(userData){
                                    wx.hideLoading();
                                    if(userData.data.code==200){
                                        console.log(userData.data);
                                        that.setUserData(userData.data.data.login_id,userData.data.data.login_token);
                                        getData();
                                    }else{
                                        console.error(data.data.msg);
                                    }
                                });
                        }
                    })
                }
            });
        }else{
            wx.showLoading({
                title: loaddingText,
                mask:true,
                success:()=>{
                    getData();
                }
            });
        }

    }
}